define(['jquery','underscore','backbone','catjs/util','async'],function($,_,Backbone,util,async){
	var module = {};

	//结构简述
	//以微博和微博列表举例
	//每一个数据项，如微博，拥有自己的视图和模型。
	//视图负责监听事件和渲染数据
	//模型负责监听数据改变并通知视图
	//视图集合监听模型集合的增减来增减DOM节点


	//微博动作对话框
	var WeiboDialog = Backbone.View.extend({
		el : $('#dialog2'),
		events : {
			'click .post' : 'post',
			'click .transmit' : 'transmit',
			'click .confirm' : 'rmConfirm',
			'click .cancel' : 'rmCancel',
			'click .msg-send' : 'sendMsg',
		},
		//显示对话框
		postDlg : function(){
			$('#dialog2 .dialog1-wrap').css({
				'width' : 450,
				'top' : 100,
			});
			$('#dialog2 .dialog1-hd').html('发布微博');
			$('#dialog2 .dialog1-bd').html( $('#tplAddWeibo').text() );
			$('#dialog2').fadeIn();
			$('#shadow2').fadeIn();
		},
		transmitDlg : function(){
			$('#dialog2 .dialog1-wrap').css({
				'width' : 450,
				'top' : 100,
			});
			$('#dialog2 .dialog1-hd').html('转发微博');
			$('#dialog2 .dialog1-bd').html( 
				util.ejs.render( $('#tplTranWeibo').text(),this.model.attributes)
			);
			$('#dialog2').fadeIn();
			$('#shadow2').fadeIn();
		},
		removeDlg : function(){
			$('#dialog2 .dialog1-wrap').css({
				'width' : 300,
				'top' : 200,
			});
			$('#dialog2 .dialog1-hd').html('删除微博');		
			$('#dialog2 .dialog1-bd').html( $('#tplRmWeibo').text() );
			$('#dialog2').fadeIn();
			$('#shadow2').fadeIn();
		},
		//私信对话框
		privateMsgDlg : function(){
			$('#dialog2 .dialog1-hd').html('发送私信');
			$('#dialog2 .dialog1-bd').html($('#tplPrivateMsg').text());
			$('#dialog2').fadeIn();
			$('#shadow2').fadeIn();
		},		
		//发送微博
		post : function(){
			var self = this;
			var placeId , type , userId , content , replyType;
			placeId = self.model.id;
			type = self.model.type;
			userId = util.getUser().userId;
			content = self.$el.find('textarea[name=content]').val();
			replyType = 1;
			self.$el.find('input[name=replyType]').each(function(i,e){
				e.checked ? replyType = e.value : 0;
			});
			$.ajax({
				url : '/Weibo/Add',
				type : 'POST',
				data : {
					placeId : placeId,
					type : type,
					userId : userId,
					content : content,
					replyType : replyType,
				},
				success : function(data){
					//将微博渲染到视图
					self.model.add(JSON.parse(data));
					$('#dialog2').fadeOut();
					$('#shadow2').fadeOut();
				},
			});
		},
		//转发微博
		transmit : function(){
			var self = this;
			var placeId , type , originBlogId , userId , tranReason , replyType;
			placeId = self.model.id;
			type = self.model.type;

			originBlogId = self.model.attributes.originalBlog.originalBlogId;
			userId = util.getUser().userId;
			tranReason = self.$el.find('textarea[name=tranReason]').val();
			replyType = 1;
			self.$el.find('input[name=replyType]').each(function(i,e){
				e.checked ? replyType = e.value : 0;
			});
			$.ajax({
				url : '/Weibo/Transmit',
				type : 'POST',
				data : {
					placeId : placeId,
					type : type,
					originBlogId : originBlogId,
					userId : userId,
					tranReason : tranReason,
					replyType : replyType,
				},
				success : function(data){
					//渲染视图
					self.model.collection.add(JSON.parse(data));
					$('#dialog2').fadeOut();
					$('#shadow2').fadeOut();
				},
			});
		},
		//删除确定
		rmConfirm : function(){
			var self = this;
			var type , blogId;
			//微博类型
			switch( self.model.rmType ){
				case 'transmit':
					type = 'transmit';
					blogId = self.model.attributes.tranBlog.tranMicroBlogId;
					break;
				case 'original':
					type = 'original';
					blogId = self.model.attributes.originalBlog.originalBlogId;
					break;
			}
			$.ajax({
				url : '/Weibo/Remove',
				type : 'DELETE',
				data : {
					type : type,
					blogId : blogId,
				},
				success : function(){
					//在视图上删除微博
					self.model.collection.remove(self.model);
					self.model.trigger('destoryed');
					$('#dialog2').fadeOut();
					$('#shadow2').fadeOut();
				}
			});
		},
		//取消删除
		rmCancel : function(){
			var self = this;
			$('#dialog2').fadeOut();
			$('#shadow2').fadeOut();
		},
		//发送私信
		sendMsg : function(){
			var self = this;
			var content = self.$el.find('textarea[name=content]').val();
			$.ajax({
				url : '/Weibo/AddMsg',
				type : 'POST',
				data : {
					msgContent : content,
					msgFrom : util.getUser().userId,
					msgTo : self.model.userId,
				},
				success : function(){
					$('#dialog2').fadeOut();
					$('#shadow2').fadeOut();
				},
			});
		},

	});
	var weiboDialog = new WeiboDialog;
	//个人信息视图
	var CitizenCard = Backbone.View.extend({

		template : $('#tplCitizenCard').text(),
		el : $('.citizen-card'),
		events : {
			//关注
			'click .add-focus' : 'addFocus',
			'click .rm-focus' : 'rmFocus',
			//拉黑
			'click .add-black' : 'addBlack',
			'click .rm-black' : 'rmBlack',
			//私信
			'click .add-msg' : 'addMsg',
		},

		render : function(x,y){
			var self = this;
			$('.citizen-card').fadeIn().css({
				'left' : x,
				'top' : y,
			}).html( util.ejs.render(self.template,self.model) );
			$('#dialog3,#dorm-building').click(function(){
				$('.citizen-card').fadeOut();
			});
		},	
		//增加关注
		addFocus : function(){
			var self = this;
			$.ajax({
				url : '/Weibo/AddFocus',
				type : 'GET',
				data : {
					from : util.getUser().userId,
					to : self.model.userId,
				},
				success : function(){
					self.$el.find('.add-focus').addClass('rm-focus').removeClass('add-focus').html('取消关注');
				},
			});
		},
		//删除关注
		rmFocus : function(){
			var self = this;
			$.ajax({
				url : '/Weibo/RemoveFocus',
				type : 'GET',
				data : {
					from : util.getUser().userId,
					to : self.model.userId,
				},
				success : function(){
					self.$el.find('.rm-focus').addClass('add-focus').removeClass('rm-focus').html('关注');
				},
			});
		},
		//增加拉黑
		addBlack : function(){
			var self = this;
			$.ajax({
				url : '/Weibo/AddBlack',
				type : 'GET',
				data : {
					from : util.getUser().userId,
					to : self.model.userId,
				},
				success : function(){
					self.$el.find('.add-black').addClass('rm-black').removeClass('add-black').html('取消拉黑');
				},
			});
		},
		//删除拉黑
		rmBlack : function(){
			var self = this;
			$.ajax({
				url : '/Weibo/RemoveBlack',
				type : 'GET',
				data : {
					from : util.getUser().userId,
					to : self.model.userId,
				},
				success : function(){
					self.$el.find('.rm-black').addClass('add-black').removeClass('rm-black').html('拉黑');
				},
			});
		},
		//增加私信
		addMsg : function(){
			var self = this;
			weiboDialog.model = self.model;
			weiboDialog.privateMsgDlg();
		},
	});
	var citizenCard = new CitizenCard;
	//导出citizenCard
	module.citizenCard = citizenCard;
	//评论列表模型
	var CommentList = Backbone.Collection.extend({

	});
	//评论视图
	var CommentView = Backbone.View.extend({
		
		tagName : 'dl',
		template : $('#tplComment').text(),
		events : {
			'click .remove' : 'remove',
		},

		render : function(){
			var self = this;
			self.$el.html(util.ejs.render(self.template,self.model.attributes));
			return self.$el;
		},
		//删除评论
		remove : function(){
			var self = this;
			var type , commentId;
			var weibo = self.model.collection.weibo.attributes;
			if( weibo.tranBlog ){
				type = 'transmit';
			}else{
				type = 'original';
			}
			commentId = self.model.attributes.comment.commentId;
			$.ajax({
				url : '/Weibo/RemoveComment',
				type : 'DELETE',
				data : {
					type : type,
					commentId : commentId,
				},
				success : function(){
					self.model.collection.remove(self.model);
					self.remove();
				},
			});
		},
	});
	//评论列表视图
	var CommentListView = Backbone.View.extend({
		
		el : $( $('#tplWeiboCmtList').text() ),
		events : {
			'click .btn-reply' : 'reply',
		},

		render : function(){
			var self = this;
			//监听事件
			self.model.bind('add',self.addComment,self);			
			//清空模型和视图
			self.$el.filter(':last').children('dl').remove();
			$('#dialog1 .dialog1-bd').empty().append( self.$el );
			//重设dialog宽度
			$('#dialog1 .dialog1-wrap').css('width',720);
			//微博
			self.$el.children('dl:first').html(
				util.ejs.render($('#tplWeibo').text(),self.model.weibo.attributes)				
			);
			//评论列表
			self.model.models.forEach(function(model){
				self.addComment(model,model.collection);
			});

			$('#dialog1').fadeIn();
			$('#shadow1').fadeIn();
		},
		//评论增加时自动渲染方法
		addComment : function(model,collection){
			var self = this;
			var commentView = new CommentView;
			commentView.model = model;
			self.$el.filter(':last').prepend( commentView.render() );
		},
		reply : function(){
			var self = this;
			var type , blogId , userId , comment;
			var weibo = self.model.weibo.attributes;
			if( weibo.tranBlog ){
				type = 'transmit';
				blogId = weibo.tranBlog.tranMicroBlogId;
			}else{
				type = 'original';
				blogId = weibo.originalBlog.originalBlogId;
			}
			userId = util.getUser().userId;
			comment = self.$el.find('textarea[name=content]').val();
			$.ajax({
				url : '/Weibo/AddComment',
				type : 'POST',
				data : {
					type : type,
					blogId : blogId,
					userId : userId,
					comment : comment,
				},
				success : function(data){
					self.model.add(JSON.parse(data));
					self.$el.find('textarea[name=content]').val('');
				},
			});
		},
	});
	var commentListView = new CommentListView;

	//微博列表模型
	var WeiboList = Backbone.Collection.extend({
		fetch : function(options){
			var self = this;
			$.ajax({
				url : '/Weibo/List',
				type : 'GET',
				data : {
					placeId : self.id,
					type : self.type,
				},
				success : options.success,
				error : options.error,
			});
		},
	});
	var WeiboView = Backbone.View.extend({

		tagName : 'dl',
		template : $('#tplWeibo').text(),
		events : {
			'click .btn-transmit' : 'transmit',
			'click .btn-remove' : 'originRemove',
			//转发微博的转发和删除
			'click .btn-tran-remove' : 'tranRemove',
			//微博评论列表
			'click .comment-list' : 'commentList',
			//个人信息
			'mouseenter .weibo-avatar' : 'showUserInfo',
		},
		initialize : function(){
			var self = this;
			self.model.bind('destoryed',self.destoryed,self)
		},
		render : function(){
			var self = this;
			return self.$el.html(
				util.ejs.render( self.template , self.model.attributes )
			);
		},
		transmit : function(){
			var self = this;
			weiboDialog.model =self.model;
			weiboDialog.transmitDlg();
		},
		originRemove : function(){
			var self = this;
			self.model.rmType = 'original';
			weiboDialog.model =self.model;
			weiboDialog.removeDlg();
		},
		tranRemove : function(){
			var self = this;
			self.model.rmType = 'original';
			weiboDialog.model =self.model;
			weiboDialog.removeDlg();
		},
		//模型删除时,视图同时删除
		destoryed : function(){
			var self = this;
			self.remove();
		},
		//评论列表
		commentList : function(){
			var self = this;
			var type , blogId;//type:tranmit,original
			if( self.model.attributes.tranBlog ){
				type = 'transmit';
				blogId = self.model.attributes.tranBlog.tranMicroBlogId;
			}else{
				type = 'original';
				blogId = self.model.attributes.originalBlog.originalBlogId;
			}
			$.ajax({
				url : '/Weibo/CommentList',
				type : 'GET',
				data : {
					type : type,
					blogId : blogId,
				},
				success : function(data){
					commentListView.model = new CommentList(JSON.parse(data).commenList);
					commentListView.model.weibo = self.model;
					commentListView.render();
				},
			});

		},
		//显示个人信息
		showUserInfo : function(e){
			var self = this;
			var weibo = self.model.attributes;
			var user = weibo.tranUser || weibo.originalUser;
			citizenCard.model = user;
			citizenCard.render(e.pageX,e.pageY);
		},
	});
	//微博列表视图
	var WeiboListView = Backbone.View.extend({

		tagName : 'div',
		className : 'weibo-list',
		events : {
			'click .dialog2-post' : 'post',
		},
		dialog : $('#dialog3'),
		shadow : $('#shadow3'),

		render : function(){
			var self = this;
			//增加删除微博时自动渲染
			self.model.unbind('add',self.addWeibo,self);
			self.model.bind('add',self.addWeibo,self);
			//初始微博列表
			self.$el.empty();
			self.$el.append('<a href="#" class="dialog2-post">发言</a>');			
			self.model.models.forEach(function(model){
				self.addWeibo(model,self.model);
			});			

			self.dialog.find('.dialog2-body').append( self.$el );
			self.dialog.fadeIn();
			self.shadow.fadeIn();
		},
		post : function(){
			var self = this;
			weiboDialog.model =self.model;
			weiboDialog.postDlg();
		},
		//增加微博时自动渲染
		addWeibo : function(model,collection){
			var self = this;
			model.type = collection.type;
			model.id = collection.id;
			var weiboView = new WeiboView({model:model});
			self.$el.prepend( weiboView.render() );
		},
	});
	var listView = new WeiboListView;
	//path微博列表视图
	var SoundView = Backbone.View.extend({

		template : $('#tplSound').text(),
		events : {
			'click .sound-river,.sound-emitter,h2' : 'showWeiboList',
		},

		initialize : function(){
			var self = this;
			//列表改变重绘sound视图	
			self.model.bind('add',self.render,self);
			self.model.bind('remove',self.render,self);
		},
		render : function(){
			var self = this;
			var context = self.filter(self.model);
			self.$el.find('.sound-river,.sound-emitter').remove();
			self.$el.append( util.ejs.render(self.template,context) );
		},
		filter : function(weibolist){
			var self = this;
			var className , style , first , second;
			switch( self.options.type ){
				case 'n':
					className = 'emitter';
					style = 'left:{0}px;top:{1}px;';
					first = 50;
					second = 100;
					break;
				case 's':
					className = 'emitter';
					style = 'left:{0}px;bottom:{1}px;';
					first = 50;
					second = 100;
					break;
				case 'w':
					className = 'emitter';
					style = 'left:{0}px;top:{1}px;';
					first = 100;
					second = 50;
					break;
				case 'e':
					className = 'emitter';
					style = 'right:{0}px;top:{1}px;';
					first = 100;
					second = 50;
					break;
				case 'ns':
					className = 'river';
					style = 'left:{0}px;bottom:{1}px;';
					first = 200;
					second = 100;
					break;
				case 'we':
					className = 'river';
					style = 'left:{0}px;bottom:{1}px;';
					first = 200;
					second = 100;
					break;
			}
			return self.format(weibolist,className,style,first,second);
		},
		format : function(weibolist,className,style,first,second){
			var context = {};
			context.bubbles = [];
			context.className = className;
			weibolist.models.forEach(function(model){
				var weibo = model.attributes;
				var bubble = {};
				if( weibo.tranBlog ){//转发微博
					bubble.content = weibo.tranBlog.tranReason;
				}else{//原始微博
					bubble.content = weibo.originalBlog.blogContent;
				}
				bubble.style = style.format(
					util.randomInt(first),util.randomInt(second)
				);
				bubble.layer = util.randomInt(0,2);
				context.bubbles.push(bubble);
			});
			return context;
		},
		//显示微博列表
		showWeiboList : function(){
			var self = this;
			listView.model = self.model;
			listView.render();
		},
	});

	//微博列表缓存
	var streetWeiboCache = {};
	var buildingWeiboCache = {};

	//加载微博模块
	module.loadWeibo = function(node,nodeView){
		//加载街道微博
		node.paths.forEach(function(path){
			if( path.street_id ){//path在street上
				var weibolist;
				if( weibolist = streetWeiboCache[path.street_id] ){//已缓存
					//创建sound view
					var soundView = new SoundView({
						model:weibolist,
						el:nodeView.find('.path.path-'+path.type),
						type : path.type,
					});
					//渲染sound view
					soundView.render();
				}else{//未缓存,加载
					weibolist = new WeiboList;
					weibolist.id = path.street_id;
					weibolist.street_id = path.street_id;
					weibolist.type = 'street';
					weibolist.fetch({
						success : function(data){
							//解析保存返回数据
							var weibos = JSON.parse(data);
							weibos.forEach(function(weibo){
								//判断微博类型
								weibolist.add(weibo);
							});				
							//缓存
							//再次检测是否已经缓存
							//存在两个path具有相同street_id同时fetch
							if( streetWeiboCache[path.street_id] ){
								weibolist = streetWeiboCache[path.street_id];
							}else{
								streetWeiboCache[path.street_id] = weibolist;	
							}
								
							//创建sound view
							var soundView = new SoundView({
								model:weibolist,
								el:nodeView.find('.path.path-'+path.type),
								type : path.type,
							});

							//渲染sound view
							soundView.render();
						},
					});
				}
			}
			//加载建筑微博
			path.buildings.forEach(function(building){
				var weibolist;
				if( weibolist = buildingWeiboCache[building.building_id] ){//已缓存
					//不操作
					;
				}else{//未缓存,加载
					weibolist = new WeiboList;
					weibolist.id = building.building_id;
					weibolist.building_id = building.building_id;
					weibolist.type = 'building';
					weibolist.fetch({
						success : function(data){
							//解析保存返回数据
							var weibos = JSON.parse(data);
							weibos.forEach(function(weibo){
								//判断微博类型
								weibolist.add(weibo);
							});				
							//缓存
							//再次检测是否已经缓存
							//存在两个path具有相同street_id同时fetch
							if( buildingWeiboCache[building.building_id] ){
								weibolist = buildingWeiboCache[building.building_id];
							}else{
								buildingWeiboCache[building.building_id] = weibolist;	
							}
						},
					});
				}
			});
		});


	};
	//显示建筑物微博列表
	module.showBuildingWeiboList = function(building_id){
		var weibolist = buildingWeiboCache[building_id];
		listView.model = weibolist;
		listView.render();
	};

	return module;
});